package com.healthy.junit;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.healthy.entity.YgAdmins;
import com.healthy.entity.YgDocument;
import com.healthy.entity.YgUsers;
import com.healthy.entity.YgWallet;
import com.healthy.mapper.YgDocumentMapper;
import com.healthy.mapper.YgUsersMapper;
import com.healthy.mapper.YgWalletMapper;
import com.healthy.util.Dateutil;
import com.healthy.util.EncryptUtil;

/**
 * @author Maple.Chen
 * @date 2020年6月10日
 * @description <p>文章（Document）相关接口-单元测试</p>
 */
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
//RunWith的value属性指定以spring test的SpringJUnit4ClassRunner作为启动类 [如果不指定启动类，默认启用的junit中的默认启动类]
@RunWith(value = SpringJUnit4ClassRunner.class)
public class DocumentTest {

	@Autowired
	private SqlSessionFactory sessionFactory;
	
	/*
	 * 保存文章
	 */
//	@Test
	public void Asave(){
		// 设置openSession(true)自动提交事务
		SqlSession session= sessionFactory.openSession(true);
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		YgDocument yg = new YgDocument();
		yg.setTitle("标题1");
		yg.setContent("1111111111");
		try {
			yg.setPostTime(Dateutil.getCurrentDateTime());
			System.out.println(Dateutil.getCurrentDateTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		yg.setType("时尚fashion");
		yg.setPriority(0);
		yg.setHead_img("/upresource/img/02/gt.png");
		YgAdmins ya = new YgAdmins();
		ya.setAid("7a2910d7aac811eaa0d100163e30f043");
		yg.setAdmins(ya);
		int kk = mapper.saveCharpter(yg);
		System.out.println(kk);
		
	}
	
	/*
	 * 测试MD5一次和二次加密
	 */
	@Test
	public void Bencrypt(){
		System.out.println("result^1   "+EncryptUtil.getMD5String("abcde"));
		System.out.println("result^2   "+EncryptUtil.getMD5String(EncryptUtil.getMD5String("abcde")));
	}
	
	/*
	 * 将文章的所有分类查询出来List
	 */
//	@Test
	public void CqueryTypes(){
		SqlSession session= sessionFactory.openSession();
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		List<String> types = mapper.queryAllCharpterTypes();
		for(String t:types)
			System.out.println(t);
	}
	
	/*
	 * 查询所有的文章，分页插件List
	 */
//	@Test
	public void DqueryAllOfCharpters(){
		System.err.println("查询所有文章  Start");
		SqlSession session= sessionFactory.openSession();
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		
		PageHelper.startPage(1, 10);
        List<YgDocument> list = mapper.queryAllOfCharpters();
        System.out.println(list.size());
        /*
            由于使用分页插件的方法包含了级联查询的方法，即@Many或@One
            所以需要在该方法所涉及的所有实体类上标注@JsonIgnoreProperties(value = {"handler"})注解
            以解决序列化报错问题
         */
        //生成分页信息对象
        PageInfo<YgDocument> pageInfo = new PageInfo<>(list);
        
        System.out.println(pageInfo.toString());
        System.err.println("查询所有文章  End");
	}
	// select c.did,type,title,content,postTime,head_img,   a.aid,username,password,nickname,powerValue   from yg_document c inner join yg_admins a   on c.aid=a.aid
	
	/*
	 * 管理员查看自己发布的文章List
	 */
//	@Test
	public void EqueryCharptersByAdminId(){
		System.err.println("管理员查看自己发布的所有文章  Start");
		SqlSession session= sessionFactory.openSession();
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		PageHelper.startPage(1, 4);
		List<YgDocument> list = mapper.queryCharptersByAdminId("7a2910d7aac811eaa0d100163e30f043");
		PageInfo<YgDocument> pageInfo = new PageInfo<>(list);
		System.out.println(">>>"+pageInfo.toString());
		System.err.println("管理员查看自己发布的所有文章  End");
	}
	
	/*
	 * 按条件搜索相关文章List
	 */
//	@Test
	public void FqueryCharptersByCondition(){
		System.err.println("按条件搜索相关文章  Start");
		SqlSession session= sessionFactory.openSession();
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		PageHelper.startPage(1, 4);
//		List<YgDocument> list = mapper.queryCharptersByCondition("瓜果类", "哈密", "缓解焦虑", "2020/06/10", null);
		List<YgDocument> list = mapper.queryCharptersByCondition(null, null, "缓解焦虑", "2020/06/10", "2020/09/03");
		PageInfo<YgDocument> pageInfo = new PageInfo<>(list);
		
		System.out.println(">>>"+pageInfo.toString());
		System.err.println("按条件搜索相关文章  End");
	}
	
	/*
	 * 查询某篇文章
	 */
//	@Test
	public void GqueryCharpterById(){
		SqlSession session= sessionFactory.openSession();
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		YgDocument yd = mapper.queryCharpterById("30f4fa92acad11eaa0d100163e30f043");
		System.out.println(yd.toString());
	}
	
	/*
	 * 修改文章
	 */
//	@Test
	public void HupdateCharpter(){
		SqlSession session= sessionFactory.openSession();
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		YgDocument yd = new YgDocument();
		// 根据id修改信息
		yd.setDid("30f4fa92acad11eaa0d100163e30f043");
		// 需要更改的信息
		yd.setTitle("11111");
		yd.setContent("11111111111111");
		yd.setType("电子类");
		yd.setHead_img("/source/aa.jpeg");
		yd.setPriority(1);
		// 必须填充的属性
		try {
			yd.setPostTime(Dateutil.getCurrentDateTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		int affectLine = mapper.updateCharpter(yd);
		if(affectLine > 0){
			System.out.println("修改成功");
		}else{
			System.out.println("修改失败");
		}
		
		
	}
	
	/*
	 * 删除文章
	 */
//	@Test
	public void IdeleteCharpter(){
		SqlSession session= sessionFactory.openSession();
		YgDocumentMapper mapper = session.getMapper(YgDocumentMapper.class);
		
		int affectLine = mapper.deleteCharpter("30f4fa92acad11eaa0d100163e30f043");
		
		if(affectLine > 0){
			System.out.println("删除成功");
		}else{
			System.out.println("删除失败");
		}
		
	}
	
	/**
	 * 
	 */
//	@Test
	public void JUserInitWallet(){
		SqlSession session= sessionFactory.openSession();
		YgUsersMapper mapper = session.getMapper(YgUsersMapper.class);
		YgWalletMapper m2 = session.getMapper(YgWalletMapper.class);
		// 1.查询用户与余额
//		System.out.println(mapper.findUserById("7a7d11ff-abfc-11ea-a0d1-00163e30f043"));
		// 2.用户注册并初始化账户
//		YgUsers yu = new YgUsers();
//		yu.setUsername("test123");
//		yu.setPassword(EncryptUtil.getMD5String(EncryptUtil.getMD5String("51351648")));
//		yu.setNickname("testtt");
//		yu.setMobile("test10086");
//		yu.setEmail("test@qq.com");
//		yu.setSex("男");
//		boolean result = mapper.userRegister(yu);
//		System.out.println(result+" 渲染的uid>"+yu.getUid());
//		m2.initUserWallet(yu.getUid());
		// 3.修改账户余额
		// 查询账户余额
		YgWallet ywwe = m2.queryUserSurplusByUid("5bf5ef66ad8111eaa0d100163e30f043");
		BigDecimal yue = ywwe.getSurplus(); // 用户余额假设为￥1.10
		YgWallet yw = new YgWallet();
		// BigDecimal有三种构造转化：整型int,双精度型double,以及字符串型String,(常用int和String即可，double不推荐使用)
		// 3.(1)构造转化String：单价
		BigDecimal unitPrice = new BigDecimal("49.22");
		// 3.(2)构造转化int：下单数量
		BigDecimal amount = new BigDecimal(10);
		// 计算交易总额
		BigDecimal total = unitPrice.multiply(amount);  // 交易总额设为￥492.20
		// 判断用户余额是否足以完成本次交易
		System.out.println(yue.compareTo(total));  // -1
		System.out.println(total.compareTo(yue));  // 1
		// 修改余额
//		yw.setId("5bf5ef66ad8111eaa0d100163e30f043");
//		yw.setSurplus(total);
//		yw.setIntegral(-99);
//		int affectLine = m2.updateUserSurplus(yw);
//		System.out.println("修改结果 " + (affectLine > 0));
		
		/*
		 * 由于当前数据库sql_mode，所以积分和余额都为整数，若存负数会报out of range Exception
		 * @unsigned 严格模式，对于数字即表现为无符号化(意为只能存正数)，对于date类型字段来说，只能存符合规范的date数据，诸如此等
		 * @zerofill 表示数字前填充零，如13，在decimal(5,2)下表现为：013.00
		 * `surplus` decimal(18,2) unsigned zerofill DEFAULT NULL COMMENT '余额',
  		 * `integral` int(10) unsigned zerofill DEFAULT NULL COMMENT '积分',
		 */
	}

}
